from odoo import fields, models, api
from odoo.exceptions import UserError

from .rp_shipment import TRACKING_STATE


class RPShipmentTracking(models.Model):
    _name = 'rp.shipment.tracking'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _description = '运输追踪'
    _rec_name = 'code'

    def _default_get_hours(self):
        hours = self.env['uom.uom'].search([('name', '=', 'Hours')])
        return hours.id if hours else False

    code = fields.Char(string='订单单号', default='RP_ST/20230101/*****', readonly=True, copy=False, index=True, tracking=True)
    rp_shipment_id = fields.Many2one(string='运单', comodel_name='rp.shipment')
    state = fields.Selection(string='状态', selection=TRACKING_STATE, compute='_depends_update_info', store=True)

    first_state_dt = fields.Datetime(string='开始时间', compute='_depends_update_info', store=True)
    estimate_delivery_dt = fields.Datetime(string='预期送达时间')
    delivered_dt = fields.Datetime(string='实际送达时间', compute='_depends_update_info', store=True)

    late_flag = fields.Boolean(string='延误', default=False, compute='_depends_compute_late', store=True)
    late_time = fields.Float(string='延误时间', compute='_depends_compute_late', store=True, help='时间段')
    time_uom_id = fields.Many2one(string='时间单位', comodel_name='uom.uom', domain=[('category_id', '=', 3)], default=_default_get_hours)

    rp_shipment_tracking_line_ids = fields.One2many(string='关联运输追踪明细', comodel_name='rp.shipment.tracking.line', inverse_name='rp_shipment_tracking_id')

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.shipment.tracking') or '/'
        return super(RPShipmentTracking, self).create(vals_list)

    @api.depends('rp_shipment_tracking_line_ids.update_state')
    def _depends_update_info(self):
        """ 更新状态、时间 """
        for s in self:
            if s.rp_shipment_tracking_line_ids:
                # 过滤出有有效 update_dt 的记录
                valid_lines = s.rp_shipment_tracking_line_ids.filtered(lambda r: r.update_dt)
                if valid_lines:
                    # 按 update_dt 排序并获取最新的记录
                    latest_line = valid_lines.sorted(key=lambda r: r.update_dt, reverse=True)[0]
                    start_line = valid_lines.sorted(key=lambda r: r.update_dt, reverse=False)[0]
                    end_line = valid_lines.filtered(lambda i: i.update_state == TRACKING_STATE[3][0])

                    s.write({'state': latest_line.update_state,
                             'first_state_dt': start_line.update_dt,
                             'delivered_dt': end_line.update_dt if end_line else False})

    @api.depends('delivered_dt', 'estimate_delivery_dt')
    def _depends_compute_late(self):
        for s in self:
            # 检查是否延误及计算延误时间
            if s.delivered_dt and s.estimate_delivery_dt:
                # 判断是否延误
                if s.delivered_dt > s.estimate_delivery_dt:
                    # 计算延误时间，单位为小时
                    delay = s.delivered_dt - s.estimate_delivery_dt
                    s.write({'late_flag': True,
                             'late_time': delay.total_seconds() / 3600})
                else:
                    s.write({'late_flag': False,
                             'late_time': 0.0})
            else:
                s.write({'late_flag': False,
                         'late_time': 0.0})


class RPShipmentTrackingLine(models.Model):
    _name = 'rp.shipment.tracking.line'
    _description = '运输追踪明细'
    _order = 'update_dt DESC'

    rp_shipment_tracking_id = fields.Many2one(string='关联运输追踪', comodel_name='rp.shipment.tracking', ondelete='cascade')

    update_dt = fields.Datetime(string='更新时间')
    update_state = fields.Selection(string='更新状态', selection=TRACKING_STATE)
    update_city = fields.Many2one(string='更新城市', comodel_name='res.city')

    description = fields.Text(string='更新信息')
